<template>
  <div class="chart-renderer">
    <div class="chart-title" v-if="title">{{ title }}</div>
    <div
      ref="chartRef"
      class="chart-container"
      :style="{ width: `${width}px`, height: `${height}px` }" />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  type: {
    type: String,
    default: 'line'
  },
  title: {
    type: String,
    default: ''
  },
  width: {
    type: Number,
    default: 600
  },
  height: {
    type: Number,
    default: 400
  },
  dataSource: {
    type: String,
    default: 'static'
  },
  staticData: {
    type: String,
    default: ''
  },
  apiUrl: {
    type: String,
    default: ''
  },
  showLegend: {
    type: Boolean,
    default: true
  },
  showTooltip: {
    type: Boolean,
    default: true
  }
})

const chartRef = ref(null)
let chart = null

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表数据
const updateChart = async () => {
  if (!chart) return

  let data = null
  
  // 获取数据
  if (props.dataSource === 'static') {
    try {
      data = JSON.parse(props.staticData)
    } catch (error) {
      console.error('静态数据解析失败:', error)
      return
    }
  } else {
    try {
      const response = await fetch(props.apiUrl)
      data = await response.json()
    } catch (error) {
      console.error('接口数据获取失败:', error)
      return
    }
  }

  // 配置图表选项
  const options = {
    title: {
      text: props.title,
      show: !!props.title
    },
    tooltip: {
      show: props.showTooltip
    },
    legend: {
      show: props.showLegend
    },
    xAxis: {
      type: 'category',
      data: data?.xAxis || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        type: props.type,
        data: data?.series || []
      }
    ]
  }

  chart.setOption(options)
}

// 监听属性变化
watch(
  () => [
    props.type,
    props.title,
    props.dataSource,
    props.staticData,
    props.apiUrl,
    props.showLegend,
    props.showTooltip
  ],
  () => {
    updateChart()
  }
)

// 监听容器尺寸变化
watch(
  () => [props.width, props.height],
  () => {
    if (chart) {
      chart.resize()
    }
  }
)

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.chart-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}

.chart-container {
  margin: 0 auto;
}
</style> 